package Pixiv;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownLoad {
	private static int a=0;
	private static InputStream is;
	private static OutputStream os;
	public void newFile(String URL0,String SearchWord){
		try {
			URL url = new URL(URL0);
			HttpURLConnection connection=(HttpURLConnection) url.openConnection();
			connection.setRequestProperty("Referer", "https://www.pixiv.net");
			int code =connection.getResponseCode();
			if (code==200) {
				System.out.println("图片下载地址连接成功");
				is=connection.getInputStream();
				connection.connect();
				
				byte[] bs = new byte[1024];
				
				 int len;
				 File sf = new File(SearchWord);
				 if (!sf.exists()) {
					sf.mkdirs();
				}else
				 os=new FileOutputStream(sf.getPath()+"\\"+a+".jpg");
				 while ((len=is.read(bs))!=-1) {
					os.write(bs, 0, len);
				}
				 a++;
				 os.flush();
				 os.close();
				 is.close();
				 System.out.println("下载成功");
			}else {
				URL0=URL0.replace("jpg", "png");
				URL url1 = new URL(URL0);
				HttpURLConnection connection1=(HttpURLConnection) url1.openConnection();
				connection1.setRequestProperty("Referer", "https://www.pixiv.net");
				int code1 =connection1.getResponseCode();
				if (code1==200) {
					System.out.println("图片下载地址连接成功");
					is=connection.getInputStream();
					connection.connect();
					
					byte[] bs = new byte[1024];
					
					 int len;
					 File sf = new File(SearchWord);
					 if (!sf.exists()) {
						sf.mkdirs();
					}else
					 os=new FileOutputStream(sf.getPath()+"\\"+a+".png");
					 while ((len=is.read(bs))!=-1) {
						os.write(bs, 0, len);
					}
					 a++;
					 os.flush();
					 os.close();
					 is.close();
					 System.out.println("下载成功");
				}else {
					System.out.println("下载失败");
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("本图片下载异常"+e);
		}
	}
}


